<template>
  <div>
    <van-form @submit="onSubmit">
      <van-field v-model="shop.shopname" label="店铺名称" placeholder="请输入" :rules="[{ required: true, message: '请填写店铺名称' }]" />
      <van-field v-model="apply_type" class="select" label="申请类型" placeholder="请选择" :rules="[{ required: true, message: '请选择店铺类型' }]" is-link readonly @click="showPicker = true" />
      <van-field v-model="is_wholesale" class="select" label="是否批发" placeholder="请选择" :rules="[{ required: true, message: '请选择是否向总部批发' }]" is-link readonly @click="showWholesale = true" v-if="showChooseHolesale" />
      <van-field v-model="shop.remark" type="textarea" class="textarea" name="店铺简介" label="店铺简介" placeholder="请填写店铺简介" :rules="[{ required: true, message: '请填写店铺简介' }]" maxlength="100" autosize show-word-limit />

      <van-field v-model="shop.phone" name="电话" label="电话" placeholder="请输入电话" :rules="[{ pattern, message: '请填写正确电话号码' }]" />
      <van-field v-model="shop.shop_manager" label="店长名称" placeholder="请输入" :rules="[{ required: true, message: '请填写店长名称' }]" />
      <van-field v-model="shop.user_pass" type="password" label="账号密码" placeholder="请输入" :rules="[{ required: true, message: '请填写密码' }]" />
      <van-field v-model="area_code" class="select" label="商家地址" placeholder="请输入" :rules="[{ required: true, message: '请填写商家地址' }]" is-link readonly @click="showArea = true" />
      <van-cell title="选择街道" is-link @click="(showStreet=true)" v-model="street" />
      <van-field v-model="shop.address" label="详细地址" placeholder="请输入" :rules="[{ required: true, message: '请填写详细地址' }]" />
      <van-field v-model="shop.location" class="crevice" label="地理位置" placeholder="请选择地理位置" :rules="[{ required: true, message: '请填写地理位置' }]" is-link readonly @click="locpopup = true" />
      <!-- <van-field v-model="shop.address" label="业务员名称" placeholder="请输入" :rules="[{ required: true, message: '请填写详细业务员名称' }]" /> -->
      <van-field label="身份证" input-align="center" class="upload" :rules="[{ validator, message: '请上传身份证' }]">
        <template #input>
          <van-uploader name="idcardimg1" :after-read="updateUserImg" :before-read="beforeRead" :upload-icon="idcardimg1" :max-count="1" :max-size="5242880" @oversize="onOversize" accept=".jpg,.png" />
          <van-uploader name="idcardimg2" :after-read="updateUserImg" :before-read="beforeRead" :upload-icon="idcardimg2" :max-count="1" :max-size="5242880" @oversize="onOversize" accept=".jpg,.png" />

        </template>

      </van-field>
      <van-field label="店铺图片" input-align="center" class="upload" :rules="[{ validator:imagesurlValidator, message: '请上传店铺图片' }]">
        <template #input>
          <van-uploader :after-read="updateUserImg" name="imagesurl" :before-read="beforeRead" :upload-icon="imagesurl" :max-count="1" :max-size="5242880" @oversize="onOversize" accept=".jpg,.png" />
        </template>

      </van-field>

      <van-field label="店铺营业执照" input-align="center" class="upload" v-model="shop.licenseimg" :rules="[{ validator:licenseimgValidator, message: '请上传店铺营业执照' }]">
        <template #input>
          <van-uploader :after-read="updateUserImg" :before-read="beforeRead" name="licenseimg" :upload-icon="licenseimg" :max-count="1" :max-size="5242880" @oversize="onOversize" accept=".jpg,.png" />
        </template>

      </van-field>
      <div style="margin: 16px;">
        <van-button round block type="primary" native-type="submit">提交</van-button>
      </div>
    </van-form>
    <van-popup v-model="showPicker" position="bottom">
      <van-picker show-toolbar :columns="columns" @confirm="onConfirm" @cancel="showPicker = false" />
    </van-popup>
    <van-popup v-model="showWholesale" position="bottom">
      <van-picker title="选择是否向总部批发" show-toolbar :columns="is_wholesaleList" @confirm="onConfirmWholesale" @cancel="showWholesale=false" value-key="name" :default-index="defaultIndex" />
    </van-popup>
    <van-popup v-model="showArea" position="bottom">
      <van-area :area-list="areaList" @confirm="onConfirmArea" @cancel="showArea = false" />
    </van-popup>
    <van-popup v-model="showStreet" position="bottom">
      <van-picker title="选择街道" show-toolbar :columns="streetlist" @confirm="onConfirmStreet" @cancel="showStreet=false" value-key="name" :default-index="defaultIndex" />
    </van-popup>
    <van-popup v-model="locpopup" position="bottom" :style="{ height: '100%' }">
      <iframe id="mapPage" width="100%" height="100%" frameborder=0 src="https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=XQWBZ-ORU64-TLBUL-X423L-TTO3Z-WQBUX&referer=myapp"></iframe>
      <div class="select_location">
        <van-button type="primary" size="small" round plain @click="cancelSelectLocation" class="cancel">取消</van-button>
        <van-button type="primary" size="small" round @click="locpopup = false">确认</van-button>
      </div>
    </van-popup>
  </div>
</template>
<script>
import { areaList } from "@vant/area-data";
import { Toast } from 'vant';
export default {

  components: {

  },
  mixins: [],
  props: {

  },
  data () {
    return {
      defaultIndex: "",
      locpopup: false,
      shop: {
        shopname: "",
        apply_type: '',
        remark: '',
        phone: '',
        shop_manager: '',
        user_pass: "",
        address: "",
        province_code: "",
        city_code: "",
        area_code: '',
        idcardimg1: '',
        idcardimg2: '',
        imagesurl: '',
        licenseimg: '',
        location: "",
        lon: '',
        lat: "",
        is_wholesale: ""
      },
      streetlist: [],
      street: '',
      showStreet: false,
      apply_type: '',
      area_code: '',
      showArea: false,
      showPicker: false,
      showWholesale: false,
      showChooseHolesale: false,
      columns: [
        '线上商城', '家政服务'
      ],
      is_wholesaleList: ['否', '是'],
      is_wholesale: '',
      areaList,

      idcardimg1: require('../../assets/img/my/idcardimg1.png'),
      idcardimg2: require('../../assets/img/my/idcardimg2.png'),
      imagesurl: require('../../assets/img/my/imagesurl.png'),
      licenseimg: require('../../assets/img/my/licenseimg.png'),
      pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
    }
  },
  computed: {

  },

  mounted () {
    this.$nextTick(() => {

      window.addEventListener('message', (event) => {
        // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
        let loc = event.data;
        if (loc && loc.module == 'locationPicker') {//防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'

          this.shop.lon = loc.latlng.lng
          this.shop.lat = loc.latlng.lat
          this.shop.location = loc.poiaddress

        }
      }, false);
    });
  },
  beforeDestroy () {
    window.removeEventListener('message', (event) => {
      // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
      let loc = event.data;
      if (loc && loc.module == 'locationPicker') {//防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'

        this.shop.lon = loc.latlng.lng
        this.shop.lat = loc.latlng.lat
        this.shop.location = loc.poiaddress

      }
    }, false)
  },

  methods: {

    // 取消选择地理位置
    cancelSelectLocation () {

      this.shop.lon = ''
      this.shop.lat = ''
      this.shop.location = ''
      this.locpopup = false
    },
    goBack () {

      this.locpopup = false
    },
    onSubmit () {
      this.$axios.post(this.$api.registerShop, {
        ...this.shop
      }).then((res) => {
        if (res.data.code == 1) {
          Toast.success('注册成功');
          this.$router.go(-1)
        }
      })


    },
    // 获取地址列表
    getMyStreet (code) {
      this.$axios.get(this.$api.streetlist, {
        params: {
          area_id: code
        }
      }).then((res) => {

        this.streetlist = res.data.data
        if (this.buttonShow) {
          this.streetlist.forEach((ele, index) => {
            if (ele.name == this.street) {
              this.defaultIndex = index
            }
          })
        }
      })
    },
    //选择店铺类型
    onConfirm (value, index) {
      this.shop.apply_type = index + 1
      this.apply_type = value

      this.showPicker = false
      // if (index) {
      //     this.showChooseHolesale=false
      // }else{
      //   this.showChooseHolesale=true

      // }
      index ? this.showChooseHolesale = false : this.showChooseHolesale = true
    },

    onConfirmWholesale (value, index) {
      this.is_wholesale = value,
        this.shop.is_wholesale = index + 1
      this.showWholesale = false
    },
    //确认选择街道
    onConfirmStreet (value) {
      this.street = value.name

      this.showStreet = false
      this.shop.street_code = value.id


    },
    //确认所选地区
    onConfirmArea (value) {

      this.shop.province_code = value[0].code
      this.shop.city_code = value[1].code
      this.shop.area_code = value[2].code
      this.area_code = value[0].name + '' + value[1].name + value[2].name
      this.showArea = false
      this.getMyStreet(this.shop.area_code)
    },

    //限制上传文件大小
    onOversize () {

      Toast('文件大小不能超过 1m');
    },
    //上传前检查
    beforeRead (file) {
      if (!/\.(jpg|jpeg|png|jpg|png)$/i.test(file.name)) {
        Toast("图片类型必须是.gif,jpeg,jpg,png中的一种,请重新上传");
        return false;
      }
      if (file.size > 512000) {
        Toast("上传图片大小不能超过2mb");
      }

      return true;
    },
    //校验身份证上传
    validator () {
      if (this.shop.idcardimg1 == '' || this.shop.idcardimg2 == '') {
        return false
      } else {
        return true
      }
    },
    //上传身份证正面
    updateUserImg (file, detail) {

      let formData = new FormData();
      formData.append("image", file.file);
      formData.append("type_name", 'applyreg');


      this.$axios.post(this.$api.uploadshopimage, formData).then((res) => {

        this[`${detail.name}`] = `${this.resourceURL}/${res.data.data.file_path}`

        this.shop[`${detail.name}`] = res.data.data.file_path

      })

    },
    // 校验店铺图片
    imagesurlValidator () {
      if (this.shop.imagesurl == '') {
        return false
      } else {
        return true
      }
    },
    // 校验店铺营业执照
    licenseimgValidator () {
      if (this.shop.licenseimg == '') {
        return false
      } else {
        return true
      }
    }
  }
};
</script>
<style lang='less' scoped>
/deep/textarea {
  background: #f8f8f8;
}
button {
  background: #ff7733;
  border: 1px solid #ff7733;
}

/deep/.van-field__control {
  text-align: end;
}
.van-uploader {
  width: 140px;
  height: 94px;
  /deep/.van-uploader__wrapper {
    width: 100%;
    height: 100%;
  }
}
/deep/ .van-uploader__upload {
  width: 100%;
  height: 100%;
  background: #fff;
}
.upload {
  flex-direction: column;
  /deep/.van-cell__title {
    width: 90px;
    margin-bottom: 10px;
  }
  /deep/.van-uploader__upload-icon {
    img {
      width: 132px;
      height: 94px;
    }
  }
}
.select_location {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: space-between;
  padding: 20px;
  box-sizing: border-box;
  .van-button {
    width: 100px;
    font-weight: bold;
    font-size: 14px;
    color: white;
  }
  .cancel {
    border: none;
    //border: 1px solid rgba(0, 0, 0, 0.3);
    background: rgba(0, 0, 0, 0.3);
  }
}
.textarea {
  /deep/.van-field__value {
    padding: 8px;
    border-radius: 6px;
    background: #f8f8f8;
  }
  /deep/.van-field__control {
    text-align: left;
  }
}
</style>